package com.wechat.service.storage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.swak.annotation.FluxService;
import com.swak.entity.YesNo;
import com.wechat.config.RobotBean;
import com.wechat.dto.ContactDTO;
import com.wechat.enums.ContactType;
import com.wechat.login.Login;
import com.wechat.login.LoginService;
import com.wechat.service.ChatService;
import com.wechat.service.ContactService;
import com.wechat.service.InitializeService;

/**
 * 初始化服务
 * 
 * @author DELL
 */
@FluxService
@Service("InitializeService")
public class InitializeServiceImpl implements InitializeService {

	@Autowired
	private ChatService chatService;
	@Autowired
	private ContactService contactService;

	/**
	 * 执行业务初始化
	 */
	@Override
	@Transactional
	public void doInitialize() {

		// 当前的用户设置为联系人
		Login login = LoginService.login();

		// 是否初始化
		ContactDTO me = this.contactService.get(login.getId());
		if (me != null) {
			return;
		}

		// 初始化当前的账户
		this.createContact(login.getId(), login.getNickName(), ContactType.User, false);

		// 初始化聊天机器人
		for (RobotBean bean : RobotBean.robots()) {

			// 创建一个联系人
			ContactDTO contact = this.createContact(bean.getId(), bean.getName(), ContactType.Assistant, true);

			// 创建聊天
			this.createChat(contact);
		}
	}

	private ContactDTO createContact(String id, String name, ContactType type, boolean isFriend) {
		ContactDTO contact = ContactDTO.of().setId(id) // 主键
				.setType(type.type)// 类型
				.setNickName(name)// 名称
				.setIsFriend(isFriend ? YesNo.Yes.getType() : YesNo.No.getType());// 是否好友-会出现在好友列表
		return this.contactService.create(contact);
	}

	private void createChat(ContactDTO contact) {
		this.chatService.create(contact);
	}
}